<?php
/**
 * Copyright (C), 2016-2018, Shall Buy Life info. Co., Ltd.
 * FileName:EcService.php
 * Description: 说明
 *
 * @author lwl
 * @Create Date 2021/12/20 10:26:09
 * @Update Date 2021/12/20 10:26:09
 * @version v1.0
 */
declare(strict_types=1);

namespace Example\Services;

use Example\Constants\EcConstant;
use Example\Constants\RefundConstant;
use Example\Models\Refund;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

final class EcService implements EcConstant
{

    /**
     * FunctionName：toMemberBalance
     * Description：
     * Author：lwl
     * @param string $topic
     * @param array $params
     * @return array
     */
    public static function toMemberBalance(string $topic = 'decoration.three.year.rebate.settle', array $params): array
    {
//        $params =
//        [
//            'transactionType' => $transactionType,
//            'accountId' => $member['account_id'],
//            'relationOrder' => $orderNo,
//            'balance' => $balance,
//            'remark' => '装饰订单余额返利',
//            'memberId' => $memberId
//        ];
//        dd($params);
        try {
            \YiMQ::transaction($topic, function () use ($params) {
                \YiMQ::ec('finance@account.addBalance')->data($params)->join();
            })->delay(20 * 1000)->begin();
            return ['code' => 200, 'error_message' => ''];
        } catch (\Exception $exception) {
            Log::channel('subsidy_order')->info('EC事务给会员增加-余额-异常', ['error_message' => $exception->getMessage()]);
            return ['code' => 501, 'message' => $exception->getMessage()];
        }
    }


    /**
     * FunctionName：toMemberRedEnvelope
     * Description：将资金增加到用户红包
     * Author：lwl
     * @param array $coinLogList 推送到资金服务的数据
     * @param array $successIds 推送成功后修复指定用户的id
     * @param $model 模型
     * @param int $status 状态
     * @return mixed|void
     * @throws \Exception
     */
    public static function toMemberRedEnvelope(string $topic = 'decoration.three.year.rebate.settle', array $coinLogList, array $successIds, $model, int $status = 0): array
    {
        try {
            \YiMQ::transaction($topic, function () use ($coinLogList, $successIds, $model, $status) {
                \YiMQ::ec('coin@coin.bathAddCoin')->data(['coinLogList' => $coinLogList])->join();
                $model->query()->whereIn('id', $successIds)->update(['status' => $status]);
            })->begin();
            return ['code' => 200, 'error_message' => ''];
        } catch (\Exception $exception) {
            Log::channel('subsidy_order')->info('EC事物给会员增加-红包-异常', ['error_message' => $exception->getMessage()]);
            return ['code' => 501, 'message' => $exception->getMessage()];
        }
    }


    /**
     * FunctionName：finishMasterOrder
     * Description：
     * Author：lwl
     * @param string $orderSn
     * @return array
     */
    public static function finishMasterOrder(string $topic = 'decoration.order.cancel.ec', string $orderSn): array
    {
        try {
            \YiMQ::transaction($topic, function () use ($orderSn) {
                \YiMQ::ec('order@order.status.complete')->data(['ordersn' => $orderSn])->join();//同步订单状态已完成
            })->begin();
            return ['code' => 200, 'data' => [],];
        } catch (\Exception $exception) {
            Log::channel('master_order')->info('tcc 主动完成主订单-错误', ['error_message' => $exception->getMessage(), '订单号' => $orderSn]);
            return ['code' => 501, 'data' => [],'message' => $exception->getMessage()];
        }
    }

    /***
     * FunctionName：storeMasterOrder
     * Description：提交主订单
     * Author：lwl
     */
    public static function storeMasterOrder(string $topic = 'decoration.order.create.tcc', string $type = 'decoration_order', $amount = 0, int $memberId = 0, int $client, $waitPayStatus = 10): array
    {
        try {
            $params = [
                'order' => [
                    'client' => $client,
                    'member_id' => $memberId,
                    'status' => $waitPayStatus,
                    'type' => $type,
                    'confirm' => [
                        [
                            'storeid' => 0,
                            'deduct_coin' => 0,
                            'actual_amount' => $amount,
                            'order_amount' => $amount,
                            'return_credits' => $amount,
                            'deduct_credits' => 0,
                            'deduct_active' => 0,
                            'total_amount' => $amount,
                            'store_service_rate' => 1,
                        ]
                    ]
                ]
            ];
            $result = \YiMQ::transaction($topic, function () use ($params) {
                return \YiMQ::tcc('order@order.create.tcc')->data($params)->try();
            })->delay(1000 * 20)->begin();
            return ['code' => 200, 'data' => $result->prepareData,];
        } catch (\Exception $exception) {
            Log::channel('master_order')->info('tcc 创建主订单-异常', ['error_message' => $exception->getMessage()]);
            return ['code' => 501, 'data' => [], 'message' => $exception->getMessage()];
        }
    }


    /**
     * FunctionName：cancelMasterOrder
     * Description：关闭订单
     * Author：lwl
     */
    public static function cancelMasterOrder(string $topic = 'decoration.order.cancel.ec', string $orderSn): array
    {
        try {
            \YiMQ::transaction($topic, function () use ($orderSn) {
                \YiMQ::ec('order@order.cancel')->data(['ordersn' => $orderSn])->join();
            })->begin();
            return ['code' => 200, 'data' => [],];
        } catch (\Exception $exception) {
            Log::channel('master_order')->info('tcc 主动关闭主订单-异常', ['error_message' => $exception->getMessage(), '订单号' => $orderSn]);
            return ['code' => 501, 'data' => [],];
        }
    }


    /**
     * FunctionName：settle
     * Description：发起订单结算
     * Author：lwl
     * @param string $topic
     * @param string $orderSn
     * @return array
     */
    public static function settle(string $topic = 'decoration.order.settle', string $orderSn): array
    {
        try {
            \YiMQ::transaction($topic, function () use ($orderSn) {
                \YiMQ::ec('order@order.settle.ec')->data(['ordersn' => $orderSn])->join();
            })->begin();
            return ['code' => 200, 'data' => [],];
        } catch (\Exception $exception) {
            Log::channel('order')->info('订单结算-异常', ['订单号' => $orderSn, 'error_message' => $exception->getMessage()]);
            return ['code' => 501, 'data' => [],];
        }
    }

    /**
     * FunctionName：refundAgree
     * Description：
     * Author：lwl
     * @param string $topic
     * @param string $refundSn
     * @param int $refundWay
     * @return array
     */
    public function refundAgree($topic = 'decoration.order.refund.create', string $refundSn, int $refundWay = 1)
    {
        DB::beginTransaction();
        try {
            \YiMQ::transaction($topic, function () use ($refundSn, $refundWay) {
                \YiMQ::ec('order@order.refund.agree')->data(
                    ['refund_sn' => $refundSn, 'refund_way' => $refundWay]
                )->join();
            })->begin();
            $refund = Refund::query()->where('refund_sn', $refundSn)->first();
            if ($refund && !$refund->update(['status' => RefundConstant::STATUS_REFUND_ING])) {
                Log::channel('order')->info('订单结算-错误', ['退款单号' => $refundSn]);
                DB::rollBack();
                return ['code' => 501, 'data' => [],];
            }
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::channel('order')->info('订单结算-异常', ['退款单号' => $refundSn, 'error_message' => $exception->getMessage()]);
            return ['code' => 501, 'data' => [],];
        }
        DB::commit();
        return ['code' => 200, 'data' => [],];
    }
}
